﻿using NewLife;
using NewLife.Data;
using NewLife.Log;
using NewLife.Net;
using NewLife.Net.Handlers;
using System.IO;

namespace NetClient;

internal class Program
{
    private static void Main(string[] args)
    {
        XTrace.UseConsole();
        //FileSystemWatcher watcher = new FileSystemWatcher();
        //try
        //{
        //    // 日志文件路径
        //    string logFilePath = @"D:\ACCT\log\lcs";

        //    // 注意：这里的path是文件夹路径，不包含文件名
        //    watcher = new FileSystemWatcher(logFilePath);

        //    watcher.NotifyFilter = NotifyFilters.Attributes
        //                         | NotifyFilters.CreationTime
        //                         | NotifyFilters.DirectoryName
        //                         | NotifyFilters.FileName
        //                         | NotifyFilters.LastAccess
        //                         | NotifyFilters.LastWrite
        //                         | NotifyFilters.Security
        //                         | NotifyFilters.Size;

        //    // 是否包含子文件夹
        //    watcher.IncludeSubdirectories = true;

        //    watcher.Created += new FileSystemEventHandler(LogFile.watcher_Created);

        //    watcher.Changed += new FileSystemEventHandler(LogFile.watcher_Changed);

        //    // 是否让监控事件生效
        //    watcher.EnableRaisingEvents = true;

        //    // 启动Socker客户端
        //    LogFile.Init();

        //    // 打开连接
        //    LogFile.SocketOpen();
        //    //TestClient();
        //}
        //catch (Exception ex)
        //{
        //    XTrace.WriteException(ex);
        //}
        //Console.WriteLine("客户端已启动,开始监听文件！");

        SendFile2();
        Console.ReadKey();
       // watcher.Dispose();
    }

    //static TimerX _timer;
    //static NetServer _server;

    private static void TestClient()
    {
        var uri = new NetUri("tcp://::1:1234");
        //var uri = new NetUri("tcp://net.newlifex.com:1234");
        var client = uri.CreateRemote();
        client.Log = XTrace.Log;
        client.LogSend = true;
        client.LogReceive = true;
        client.Received += (s, e) =>
        {
            var a = e.Packet.ToStr();
            XTrace.WriteLine("客户端已收到：{0}", e.Packet.ToStr());
        };
        client.Open();

        // 循环发送数据
        for (var i = 0; i < 5; i++)
        {
            Thread.Sleep(1000);

            var str = "重建站" + (i + 1) + "产生日志";
            client.Send(str);
        }

        client.Dispose();
    }


    private static FileInfo GetFile()
    {
        var src = "D:\\ACCT\\log\\lcs".AsDirectory().GetFiles().OrderByDescending(e => e.Length).FirstOrDefault();
        src ??= "../../".AsDirectory().GetFiles().OrderByDescending(e => e.Length).FirstOrDefault();
        src ??= "data/".AsDirectory().GetFiles().OrderByDescending(e => e.Length).FirstOrDefault();
        XTrace.WriteLine("发送文件：{0}", src.FullName);
        XTrace.WriteLine("文件大小：{0}", src.Length.ToGMK());

        return src;
    }

    public void SendFile()
    {
        // 目标文件
        var file = "bigfile.bin".GetFullPath();
        if (File.Exists(file)) File.Delete(file);

        using var target = File.Create(file);

        // 简易版服务端。监听并接收文件数据，e.Message就是文件数据
        using var svr = new NetServer
        {
            Port = 12345,
            Log = XTrace.Log,
        };

        svr.Add<StandardCodec>();
        svr.Received += (s, e) =>
        {
            // 收到的所有数据全部写入文件。用户可以根据自己的协议，识别文件头和文件内容
            if (e.Message is Packet pk)
                pk.CopyTo(target);
        };

        svr.Start();

        // 本地找一个大文件
        var src = GetFile();
        var md5 = src.MD5();

        // 客户端
        var uri = new NetUri($"tcp://127.0.0.3:{svr.Port}");
        var client = uri.CreateRemote();
        client.Log = XTrace.Log;

        client.Add<StandardCodec>();
        client.Open();

        // 不能发送文件以外内容，否则服务端无法识别而直接写入文件
        //client.SendMessage($"Send File {src.Name}");

        var rs = client.SendFile(src.FullName);
        XTrace.WriteLine("分片：{0}", rs);

        //client.SendMessage($"Send File Finished!");

        Thread.Sleep(1000);

        // 验证接收文件是否完整
        target.Flush();
        target.Close();


        var dest = file.AsFile();
    }

    public static void SendFile2()
    {
        // 发送文本字符串和对象消息
        var src = GetFile();
        Thread.Sleep(1000);
        // 客户端
        var uri = new NetUri($"tcp://127.0.0.1:1227");
        var client = uri.CreateRemote();
        client.Log = XTrace.Log;

        // 加入Json编码器，用于发送Json对象
        client.Add<StandardCodec>();
        client.Add<JsonCodec>();
        client.Open();

        var a=client.SendMessage($"Send File {src.Name}");
        //Thread.Sleep(1000);

        var b=client.SendMessage(new MyFileInfo { Name = src.Name, Length = src.Length ,ProgressType=45});
        //Thread.Sleep(1000);

        var rs = client.SendLogFile(src.FullName);
        Thread.Sleep(1000);
        XTrace.WriteLine("分片：{0}", rs);

        // 发送完成消息，也可以是Json消息
        client.SendMessage($"Send File Finished!");
        Thread.Sleep(1000);

    }

    class MyFileInfo
    {
        public String Name { get; set; }

        public Int64 Length { get; set; }

        /// <summary>
        /// 进程
        /// </summary>
        public required int ProgressType { get; set; }

        public String MD5 { get; set; }
    }

}